﻿using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Write.Application.Common.Role;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.Write.Application.Handler.Role
{
    public class RoleAddCommandHandle:IRequestHandler<RoleAddCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<AccountRoleModel> AccDal;

        public RoleAddCommandHandle(IBaseRepository<AccountRoleModel> accDal)
        {
            AccDal = accDal;
        }

        public async Task<ApiResult<int>> Handle(RoleAddCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var result = AccDal.GetAll().Where(x => x.RoleId == request.RoleId).ToList();
                await AccDal.Del(result);
                List<AccountRoleModel> models = new List<AccountRoleModel>();

                foreach (var item in request.UserId)
                {
                    models.Add(new AccountRoleModel()
                    {
                        UserId = item,
                        RoleId = request.RoleId,
                    });
                }

                int count = await AccDal.AddAll(models);

                if (count > 0)
                {
                    res.Code = ApiEnum.Success;
                    res.Data = count;
                    res.Message = "分配成功";
                }
                else
                {
                    res.Code = ApiEnum.Error;
                    res.Data = count;
                    res.Message = "分配失败";
                }
                tran.Complete();
                return await Task.FromResult(res);

            }

        }


    }
}
